package com.ybt.communicate.core.parser.impl;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.ybt.communicate.core.configration.IProtocolConfig;
import com.ybt.communicate.core.exception.ProtocolException;
import com.ybt.communicate.core.manager.ProtocolTypeManager;
import com.ybt.communicate.core.parser.IProtocolParser;

public class CommonProtocolParser<E extends IProtocolConfig>{
    private Logger logger = Logger.getLogger(CommonProtocolParser.class);

    public  E parse(String protocolConfig) throws ProtocolException {
        ByteArrayInputStream temp = new ByteArrayInputStream(protocolConfig
                .getBytes());
        return parse(temp);

    }

    public E parse(InputStream protocolConfig) throws ProtocolException {
        // TODO Auto-generated method stub
        try {
            logger.debug("begin to parse protocol configration : "
                    + protocolConfig);
            SAXReader saxReader = new SAXReader();
            Document doc = saxReader.read(protocolConfig);
            Element root = doc.getRootElement();
            // 协议类型
            String type = root.attributeValue("type");
            E config = ProtocolTypeManager.getInstance()
            .createProtocolConfig(type);
            config.setProtocolType(type);
            
            // 协议id
            String id = root.attributeValue("id");
            config.setProtocolId(id);

            // 协议模式（同异步）
            String mode = root.attributeValue("mode");
            config.setProtocolMode(mode);

            // 应用服务器端
            String serverSide = root.attributeValue("serverSide");
            config.setServerSide(Boolean.valueOf(serverSide));

            // 协议模式（同异步）
            String ioDirection = root.attributeValue("ioDirection");
            config.setIODirection(ioDirection);

            //获取协议对应的解析器
            IProtocolParser parser = ProtocolTypeManager.getInstance().getProtocolParser(type);

            // 解析common节点
            Element common = root.element("common");
            if (common != null) {
                // 存在common节点
                logger.debug("begin to parse common node");
                parser.parseCommon(config, common);
            }

            // 解析request节点
            Element request = root.element("request");
            if (request != null) {
                // 存在request节点
                logger.debug("begin to parse request node");
                parser.parseRequest(config, request);
            }

            // 解析response节点
            Element response = root.element("response");
            if (response != null) {
                // 存在response节点
                logger.debug("begin to parse response node");
                parser.parseResponse(config, response);
            }
            return config;
        } catch (Exception e) {
            throw new ProtocolException(e);
        }
    }


    public String convert(E protocolConfig) throws ProtocolException {
        // TODO Auto-generated method stub
        Element root = DocumentHelper.createElement("protocol");

        // 公共配置
        root.addAttribute("id", protocolConfig.getProtocolId());
        root.addAttribute("type", protocolConfig.getProtocolType());
        root.addAttribute("mode", protocolConfig.getProtocolMode());
        root.addAttribute("ioDirection", protocolConfig.getIODirection());
        //获取协议对应的解析器
        IProtocolParser parser = ProtocolTypeManager.getInstance().getProtocolParser(protocolConfig.getProtocolType());
        if (protocolConfig.getCommonConfig() != null) {
            // 存在common配置
            parser.convertCommon(protocolConfig, root);
        }

        /*if (protocolConfig.getReqConfig() != null) {
            // 存在request配置
            parser.convertRequest(protocolConfig, root);
        }

        if (protocolConfig.getRespConfig() != null) {
            // 存在response配置
            parser.convertResponse(protocolConfig, root);
        }
*/
        return root.asXML();
    }

}
